package com.choosefine.springboot.devops.base.moudle.checkable;

import com.choosefine.springboot.devops.base.common.bean.CommonToolkitBean;
import com.choosefine.springboot.devops.base.common.component.InputMessage;
import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.config.TokenUtil;
import com.choosefine.springboot.devops.base.config.UrlUtil;
import com.choosefine.springboot.devops.base.config.WXRequestUtil;
import com.choosefine.springboot.devops.base.moudle.mp.Xml;
import com.choosefine.springboot.devops.base.result.RedisSerialize;
import com.choosefine.springboot.devops.base.serviceImpl.RedisServiceImpl;
import com.choosefine.springboot.devops.user.model.User;
import com.choosefine.springboot.devops.user.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by 邱鹏 on 2016/10/18.
 */
@Service
public class CheckEnableService {
    private static String Token = "pjbao";
    Logger log = LoggerFactory.getLogger("微信/check");
    //    @Autowired
//    TemplateConfigService tplService;
    @Autowired
    MessageService msgService;
    @Autowired
    private UserService userService;
    @Autowired
    CommonToolkitBean commonToolkitBean;
    @Autowired
    ObjectMapper jsonObjectMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisServiceImpl redisService;

    public void checkEnable(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        String echostr = request.getParameter("echostr");//随机字符串
        List<String> params = new ArrayList<String>();
        params.add(Token);
        params.add(timestamp);
        params.add(nonce);
        //1. 将token、timestamp、nonce三个参数进行字典序排序
        Collections.sort(params, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int result = 0;
                if (o1 == null) {
                    if (o2 == null) {
                        result = 0;
                    } else {
                        result = -1;
                    }
                } else {
                    result = o1.compareTo(o2);
                }
                return result;
            }
        });
        //2. 将三个参数字符串拼接成一个字符串进行sha1加密
        log.info("三个参数分别是：" + params.get(0) + "," + params.get(1) + "," + params.get(2));
//        String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
//        if (temp.equals(signature)) {
        response.getWriter().write(echostr);
//        }
    }

    public void receiveMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream in = request.getInputStream();
        //将POST流转换为XStream对象
        XStream xs = new XStream(new DomDriver());
        //将指定节点下的xml节点数据映射为对象
        xs.alias("xml", InputMessage.class);
        //将流转换为字符串
        StringBuilder xmlMsg = new StringBuilder();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            xmlMsg.append(new String(b, 0, n, "UTF-8"));
        }
        Object object = xs.fromXML(xmlMsg.toString());
        InputMessage inputMsg = jsonObjectMapper.readValue(jsonObjectMapper.writeValueAsString(object), InputMessage.class);
        requestText(inputMsg,response);
        String msgType = inputMsg.getMsgType();
        //根据消息类型获取对应的消息内容
        log.info("开发者微信号ToUserName：" + inputMsg.getToUserName());
        log.info("发送方帐号FromUserName：" + inputMsg.getFromUserName());
        log.info("消息创建时间：" + inputMsg.getCreateTime());
        log.info("消息内容：" + inputMsg.getContent());
        log.info("消息Id：" + inputMsg.getMsgId());
//        Map tplDataMap = new HashMap();
//
//        tplDataMap.put("fromUser", inputMsg.getToUserName());
//        tplDataMap.put("toUser", inputMsg.getFromUserName());
//        if (msgType.equals(MsgType.Text.toString())) {
//            msgService.text(inputMsg, tplDataMap, request, response);
//        } else if (msgType.equals(MsgType.Event.toString())) {
//            msgService.event(inputMsg, tplDataMap, request, response);
//        }
    }


    public String requestText(InputMessage inputMessage, HttpServletResponse response) throws IOException {
        if ("event".equals(inputMessage.getMsgType())) {
            event(inputMessage, response);
        }
        return null;
    }

    /**
     * 找redis根据路径键，找到路径值
     *
     * @param inputMessage
     * @return
     */
    private String event(InputMessage inputMessage, HttpServletResponse response) throws IOException {
        if ("subscribe".equals(inputMessage.getEvent())) {
            if (inputMessage.getEventKey() != null) {
                String url = inputMessage.getEventKey();
                String[] methodId = url.split("_");
                String method = redisService.get(methodId[1]);
                RedisSerialize redisSerialize =null;
                if(method !=null){redisSerialize=jsonObjectMapper.readValue(method, RedisSerialize.class);}
                if(redisSerialize!=null){
                    String title = new String(redisSerialize.getMsg().getBytes("utf-8"), "ISO8859_1");//设置主题
                    String picUrl=UrlUtil.getHttpHead()+redisSerialize.getImg();//设置图片
                    String methodUrl=UrlUtil.getHttpHead()+redisSerialize.getUrl();//设置连接
                    String xml = Xml.resultImgXML(inputMessage.getFromUserName(), inputMessage.getToUserName(), picUrl,title,methodUrl);
                    insertUser(inputMessage.getFromUserName());
                    redisService.del(methodId[1]);//把redis里的键删掉，二维码失效！
                    response.getWriter().write(xml);
                }else{
                  //以关注过一次，二维码失效==！
                }
            }
        }else if ("unsubscribe".equals(inputMessage.getEvent())){//取消关注
            User user=userService.selectByCode(inputMessage.getFromUserName());
            if(user!=null) {
                user.setStatus((byte) 2);
                userService.update(User.class, MapUtil.transBean2Map(user));
            }
        }else{
            insertUser(inputMessage.getFromUserName());
        }
        return null;
    }

    private void insertUser(String code) throws IOException {
        User user=userService.selectByCode(code);
        Map map=new HashMap();
        map.put("openid",code);
        map.put("access_token", TokenUtil.getToken());
        String url="https://api.weixin.qq.com/cgi-bin/user/info";
        JSONObject jsonObject= WXRequestUtil.getUser(UrlUtil.getUrl(url,map));
        User user1=jsonObjectMapper.readValue(jsonObject.toString(),User.class);
        if(user!=null){
            user1.setId(user.getId());
            user1.setStatus((byte) 1);
            user1.setUpdateTime(new Date());
            userService.update(User.class, MapUtil.transBean2Map(user1));
            }
        else{
            user1.setCreateTime(new Date());
            user1.setStatus((byte) 1);
            userService.save(User.class,MapUtil.transBean2Map(user1));
        }
    }

}
